package edu.cuit.zhuyimeng.framework.logging.aspect.aop;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.alibaba.ttl.TransmittableThreadLocal;
import edu.cuit.zhuyimeng.framework.common.result.CommonResult;
import edu.cuit.zhuyimeng.framework.common.result.HttpStatusCodeConstants;
import edu.cuit.zhuyimeng.framework.common.util.ServletUtils;
import edu.cuit.zhuyimeng.framework.logging.aspect.OperateLogBO;
import edu.cuit.zhuyimeng.framework.logging.aspect.annotation.OperateLog;
import edu.cuit.zhuyimeng.framework.logging.aspect.enums.OperateLogType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.IntStream;


/**
 * 日志记录切面
 */
@Aspect
@Slf4j
public class OperateLogAspect {

    /**
     * 记录操作内容的上下文
     */
    private static final TransmittableThreadLocal<String> CONTENT = new TransmittableThreadLocal<>();
    /**
     * 用于记录拓展字段的上下文
     */
    private static final TransmittableThreadLocal<Map<String, Object>> EXTENTS = new TransmittableThreadLocal<>();

   /* @Around("@annotation(operation) && !@annotation(edu.cuit.zhuyimeng.common.aspect.log.annotation.OperateLog)")
    public Object around(ProceedingJoinPoint joinPoint, Operation operation) throws Throwable {
        return executeLog(joinPoint, null, operation);
    }

    @Around("@annotation(operateLog) && !@annotation(io.swagger.v3.oas.annotations.Operation)")
    public Object around(ProceedingJoinPoint joinPoint, OperateLog operateLog) throws Throwable {
        return executeLog(joinPoint, operateLog, null);
    }

    @Around(value = "@annotation(operateLog) && @annotation(operation)", argNames = "joinPoint,operateLog,operation")
    public Object around(ProceedingJoinPoint joinPoint, OperateLog operateLog, Operation operation) throws Throwable {
        return executeLog(joinPoint, operateLog, operation);
    }*/

    @Around(value = "@annotation(operateLog)")
    public Object around(ProceedingJoinPoint joinPoint, OperateLog operateLog) throws Throwable {
        return executeLog(joinPoint, operateLog, null);
    }

    private Object executeLog(ProceedingJoinPoint joinPoint, OperateLog operateLog, Operation operation) throws Throwable {

        LocalDateTime startTime = LocalDateTime.now();
        Object result = null;
        try {
            result = joinPoint.proceed();
            if (!isLogEnable(operateLog)) {
                return result;
            }

            logging(joinPoint, operateLog, operation, startTime, result, null);
            return result;
        } catch (Throwable e) {
            logging(joinPoint, operateLog, operation, startTime, result, e);
            throw e;
        } finally {
            clearThreadLocal();
        }

    }

    private void logging(ProceedingJoinPoint joinPoint,
                         OperateLog operateLog,
                         Operation operation,
                         LocalDateTime startTime, Object result, Throwable exception) {
        OperateLogBO operateLogObj = new OperateLogBO();
        operateLogObj.setStartTime(startTime);
        // 补充用户信息
        fillUserFields(operateLogObj);
        // 补全模块信息
        fillModuleFields(operateLogObj, joinPoint, operateLog, operation);
        // 补全请求信息
        fillRequestFields(operateLogObj);
        // 补全方法信息
        fillMethodFields(operateLogObj, joinPoint, operateLog, startTime, result, exception);

        log.info(operateLogObj.toString());

        // TODO 记录日志实体(微服务日志中心)

    }

    public static void setContent(String content) {
        CONTENT.set(content);
    }

    public static void addExtends(String key, Object value) {
        if (EXTENTS.get() == null) {
            EXTENTS.set(new HashMap<>());
        }
        EXTENTS.get().put(key, value);
    }

    private static void clearThreadLocal() {
        CONTENT.remove();
        EXTENTS.remove();
    }

    private boolean isLogEnable(OperateLog operateLog) {
        if (operateLog == null) {
            return true;
        }
        return operateLog.enable();
    }

    private static void fillUserFields(OperateLogBO operateLogObj) {
        if (StpUtil.isLogin()) {
            operateLogObj.setUserId(StpUtil.getLoginId().toString());
        }
    }

    private static void fillModuleFields(OperateLogBO operateLogObj,
                                         ProceedingJoinPoint joinPoint,
                                         OperateLog operateLog,
                                         Operation operation) {
        if (operateLog != null) {
            operateLogObj.setModule(operateLog.module());
        }
        if (StrUtil.isEmpty(operateLogObj.getModule())) {
            Tag tag = getClassAnnotation(joinPoint, Tag.class);
            if (tag != null) {
                if (StrUtil.isNotEmpty(tag.name())) {
                    operateLogObj.setModule(tag.name());
                }
                if (StrUtil.isEmpty(operateLogObj.getModule()) && ArrayUtil.isNotEmpty(tag.description())) {
                    operateLogObj.setModule(tag.description());
                }
            }
        }
        // name 属性
        if (operateLog != null) {
            operateLogObj.setName(operateLog.name());
        }
        if (StrUtil.isEmpty(operateLogObj.getName()) && operation != null) {
            operateLogObj.setName(operation.summary());
        }
        // type 属性
        if (operateLog != null && ArrayUtil.isNotEmpty(operateLog.type())) {
            operateLogObj.setType(operateLog.type()[0].getType());
        }
        if (operateLogObj.getType() == null) {
            RequestMethod requestMethod = obtainFirstMatchRequestMethod(obtainRequestMethod(joinPoint));
            OperateLogType operateLogType = convertOperateLogType(requestMethod);
            operateLogObj.setType(operateLogType != null ? operateLogType.getType() : null);
        }

        operateLogObj.setContent(CONTENT.get());
        operateLogObj.setExtend(EXTENTS.get());
    }

    private static void fillRequestFields(OperateLogBO operateLogObj) {
        // 获得 Request 对象
        HttpServletRequest request = ServletUtils.getRequest();
        if (request == null) {
            return;
        }
        // 补全请求信息
        operateLogObj.setRequestMethod(request.getMethod());
        operateLogObj.setRequestUrl(request.getRequestURI());
    }

    private static void fillMethodFields(OperateLogBO operateLogObj,
                                         ProceedingJoinPoint joinPoint,
                                         OperateLog operateLog,
                                         LocalDateTime startTime, Object result, Throwable exception) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        operateLogObj.setJavaMethod(methodSignature.toString());
        if (operateLog == null || operateLog.logArgs()) {
            operateLogObj.setJavaMethodArgs(obtainMethodArgs(joinPoint));
        }
        if (operateLog == null || operateLog.logResultData()) {
            operateLogObj.setResultData(obtainResultData(result));
        }
        operateLogObj.setDuration((int) (LocalDateTimeUtil.between(startTime, LocalDateTime.now()).toMillis()));
        // （正常）处理 resultCode 和 resultMsg 字段
        if (result instanceof CommonResult<?> commonResult) {
            operateLogObj.setResultCode(commonResult.getCode());
            operateLogObj.setResultMsg(commonResult.getMsg());
        } else {
            operateLogObj.setResultCode(HttpStatusCodeConstants.SUCCESS.getCode());
        }
        // （异常）处理 resultCode 和 resultMsg 字段
        if (exception != null) {
            operateLogObj.setResultCode(HttpStatusCodeConstants.INTERNAL_SERVER_ERROR.getCode());
            operateLogObj.setResultMsg(ExceptionUtil.getRootCauseMessage(exception));
        }
    }

    private static RequestMethod obtainFirstLogRequestMethod(RequestMethod[] requestMethods) {
        if (ArrayUtil.isEmpty(requestMethods)) {
            return null;
        }
        return Arrays.stream(requestMethods).filter(requestMethod ->
                        requestMethod == RequestMethod.POST
                                || requestMethod == RequestMethod.PUT
                                || requestMethod == RequestMethod.DELETE)
                .findFirst().orElse(null);
    }

    private static RequestMethod obtainFirstMatchRequestMethod(RequestMethod[] requestMethods) {
        if (ArrayUtil.isEmpty(requestMethods)) {
            return null;
        }
        // 优先，匹配最优的 POST、PUT、DELETE
        RequestMethod result = obtainFirstLogRequestMethod(requestMethods);
        if (result != null) {
            return result;
        }
        // 然后，匹配次优的 GET
        result = Arrays.stream(requestMethods).filter(requestMethod -> requestMethod == RequestMethod.GET)
                .findFirst().orElse(null);
        if (result != null) {
            return result;
        }
        return requestMethods[0];
    }

    private static OperateLogType convertOperateLogType(RequestMethod requestMethod) {
        if (requestMethod == null) {
            return null;
        }
        return switch (requestMethod) {
            case GET -> OperateLogType.GET;
            case POST -> OperateLogType.CREATE;
            case PUT -> OperateLogType.UPDATE;
            case DELETE -> OperateLogType.DELETE;
            default -> OperateLogType.OTHER;
        };
    }

    private static RequestMethod[] obtainRequestMethod(ProceedingJoinPoint joinPoint) {
        RequestMapping requestMapping = AnnotationUtils.getAnnotation(
                ((MethodSignature) joinPoint.getSignature()).getMethod(), RequestMapping.class);
        return requestMapping != null ? requestMapping.method() : new RequestMethod[]{};
    }

    @SuppressWarnings("SameParameterValue")
    private static <T extends Annotation> T getMethodAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationClass) {
        return ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(annotationClass);
    }

    @SuppressWarnings("SameParameterValue")
    private static <T extends Annotation> T getClassAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationClass) {
        return ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass().getAnnotation(annotationClass);
    }

    private static String obtainMethodArgs(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] argNames = methodSignature.getParameterNames();
        Object[] argValues = joinPoint.getArgs();
        Map<String, Object> args = Maps.newHashMapWithExpectedSize(argValues.length);
        for (int i = 0; i < argNames.length; i++) {
            String argName = argNames[i];
            Object argValue = argValues[i];
            args.put(argName, !isIgnoreArgs(argValue) ? argValue : "[ignore]");
        }
        return JSONUtil.toJsonStr(args);
    }

    private static String obtainResultData(Object result) {
        if (result instanceof CommonResult) {
            result = ((CommonResult<?>) result).getData();
        }
        return JSONUtil.toJsonStr(result);
    }

    private static boolean isIgnoreArgs(Object object) {
        Class<?> clazz = object.getClass();
        if (clazz.isArray()) {
            return IntStream.range(0, Array.getLength(object))
                    .anyMatch(index -> isIgnoreArgs(Array.get(object, index)));
        }
        if (Collection.class.isAssignableFrom(clazz)) {
            return ((Collection<?>) object).stream()
                    .anyMatch((Predicate<Object>) OperateLogAspect::isIgnoreArgs);
        }
        if (Map.class.isAssignableFrom(clazz)) {
            return isIgnoreArgs(((Map<?, ?>) object).values());
        }
        return object instanceof MultipartFile
                || object instanceof HttpServletRequest
                || object instanceof HttpServletResponse
                || object instanceof BindingResult;
    }


}
